package main

import (
	"flag"
	"fmt"
	"github.com/nats-io/go-nats"
	"github.com/pborman/uuid"
	"log"
	"time"
)

const (
	//url   = "nats://192.168.3.125:4222"
	url11 = nats.DefaultURL
)

var (
	nc11         *nats.Conn
	encodeConn11 *nats.EncodedConn
	err11        error
)

func init() {
	if nc11, err11 = nats.Connect(url11); checkErr1(err11, func() {

	}) {
		//
		if encodeConn11, err11 = nats.NewEncodedConn(nc11, nats.JSON_ENCODER); checkErr1(err11, func() {

		}) {

		}
	}
}

func main() {
	var (
		subj = flag.String("subj", "test_data", "subject name")
	)
	flag.Parse()
	log.Println(*subj)
	startClient(*subj)

	time.Sleep(time.Second)
}

// send message to server
func startClient(subj string) {
	for i := 0; i < 5; i++ {
		id := uuid.New()
		msg := id + " hello"
		fmt.Println("subj: ", subj, "  msg: ", msg)
		if err := nc11.Publish(subj, []byte(msg)); checkErr1(err, func() {
			fmt.Println("发送失败：", err)
		}) {
			fmt.Println("发送成功的数据为：", string(msg))
		}
	}
}

func checkErr1(err error, errFun func()) bool {
	if err != nil {
		log.Println("checkErr错误：", err)
		errFun()
		return false
	}
	return true
}
